package com.fengxing.ams.pub.util;

import java.io.UnsupportedEncodingException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import com.fengxing.ams.pub.AMSException;

public class HMACUtil {
	public static final String SHA1 = "HmacSHA1";
	private static final String ISO_8859_1 = "ISO-8859-1";
	private static final String UTF_8 = "UTF-8";
	
	public static String hmac(String algo, String data, String key) {
		try {
			byte[] macData = hmac2(algo, data, key);
			byte[] hex = new Hex().encode(macData);
			return new String(hex, "UTF_8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static byte[] hmac2(String algo, String data, String key) {
		try {
			// Get an hmac key from the raw key bytes
			byte[] keyBytes = key.getBytes();
			SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algo);

			// Get an hmac_sha1 Mac instance and initialize with the signing key
			Mac mac = Mac.getInstance(algo);
			mac.init(signingKey);

			// Compute the hmac on input data bytes
			byte[] macData = mac.doFinal(data.getBytes());
			return macData;
		} catch (Exception e) {
			throw new AMSException(e.getMessage(), e);
		}
	}
}
